<template>
	<view class="index">
		<indexswiper></indexswiper>
		<card></card>
		<uni-section title="我的设备 \n(注：蓝色粗字表示主设备，黑色细字表示其它关联设备)" type="line" padding>
			<view class="grid-dynamic-box">
				<uni-grid :column="3" :highlight="true" borderColor="#03a9f4">
					<uni-grid-item v-for="(item, index) in list" :index="index" :key="index">
						<navigator v-if="item && item.uuid" :url="`/pages/detail/detail?uuid=${item.uuid}`"
							hover-class="none">
							<view class="grid-item-box" :style="{'backgroundColor': item.color}">
								<text class="text1" :style="item.fontStyle">{{ item.name }}</text>
							</view>
						</navigator>
					</uni-grid-item>
				</uni-grid>
			</view>
		</uni-section>
	</view>
</template>

<script>
	import indexswiper from '@/components/index/indexswiper.vue';
	import card from '@/components/common/card.vue';
	import list from '../../uni_modules/uview-ui/libs/config/props/list';
	import {
		client
	} from '../../main.js';

 	import alarm_ from './alarm.mp3';
 	import other_ from './other.mp3';
	import sleep_ from './sleep.mp3';
 	import timeup_ from './timeup.mp3';
 	import normal_ from './normal.mp3';
 	import comforta_ from './comforta.mp3';
 	import uncomforta_ from './uncomforta.mp3';
 	

	export default {
		data() {
			return {
				list: [],
				deviceUUID: '',
				deviceUUIDlist: [],
				phoneNumber: '',
				subscribeInfo: [],
				subscribedTopics: [], // 新增已订阅主题列表
				initialized: false, // 标识是否已初始化订阅
				//录音有关值初始化
				 audio_paths: {
					alarm: alarm_,
					other: other_,
					sleep: sleep_,
					timeup: timeup_,
					normal: normal_,
					comforta: comforta_,
					uncomforta: uncomforta_	
				},
				defaultAudioPaths: {
					alarm: alarm_,
					other: other_,
					sleep: sleep_,
					timeup: timeup_,
					normal: normal_,
					comforta: comforta_,
					uncomforta: uncomforta_	
				}, 
				audioChoice: {}, // 记录每个设备的音频选择
				currentAudioContext: null, // 保存当前播放的音频对象
				audioTimeout: null // 保存音频定时器
			}
		},
		components: {
			indexswiper,
			card
		},
		onShow() {
			this.phoneNumber = uni.getStorageSync('userPhoneNumber');
			if (!this.phoneNumber) {
				this.list = [];
				console.error("未找到存储的手机号，请确保用户已登录并且手机号已被正确保存。")
			} else {
				this.getDeviceList()
			}
			if (!this.initialized) {
				this.subscribeToAllTopics();
			}
			// 加载设备的音频选择
			this.loadAudioChoices();
		},

		methods: {
			// 验证是否为有效的deviceUUID方法
			isValidUUID(deviceUUID) {
				const regex = /^LSY\/DEVICE\/YC\/[0-9a-fA-F]{12}$/;
				return regex.test(this.deviceUUID);
			},
			onNavigationBarButtonTap(e) {
				if (e.float == 'right') {
					if (!this.phoneNumber) {
						uni.showToast({title: '请登录', icon: 'none', duration: 2000});
						return; // 退出函数，不进行扫码
					}
					// 允许从相机和相册扫码
					uni.scanCode({
						success: (res) => {
							this.deviceUUID = res.result;
							let deviceUUID = this.deviceUUID.substring(14, this.deviceUUID.length);

							//验证是否为有效的UUID
							if (this.isValidUUID(deviceUUID)) {
								let deviceExists = this.list.some(item => item && item.uuid === deviceUUID);
								if (!deviceExists) {
									this.list.push({
										uuid: deviceUUID, // 保存扫描到的UUID
									});
									// 正确扫码后验证device是否有机主
									uni.request({
										url: this.$baseUrl + '/user/device/is-bonded/' + deviceUUID,
										methods: 'POST',
										data: {},
										header: {
											'content-type': 'application/x-www-form-urlencoded', // 设置请求头
											'token': uni.getStorageSync('token')
										},
										success: (res) => {
											console.log('请求成功', res); //111
											if (res.statusCode === 200) {
												// 请求成功处理:看设备是否被绑定，首先，如果没被绑定
												if (res.data.data.bonded === false) {
													uni.navigateTo({
														url: '/pages/personal/personal?uuid=' + encodeURIComponent(deviceUUID)
													});
												} else {
													uni.request({
														url: this.$baseUrl +
															'/user/device/add/alt-phone/' +
															this.phoneNumber + '/' +
															encodeURIComponent(deviceUUID),
														method: 'POST',
														header: {
															'content-type': 'application/x-www-form-urlencoded', // 设置请求头
															'token': uni.getStorageSync(
																'token')
														},
														success: (res) => {
															if (res.statusCode === 200) {
																console.log('请求成功', res); //111
																this.getDeviceList()
															}
														}
													})
												}
											}
										},
										fail: (err) => {
											// 网络或其他错误处理
											console.error('请求错误：', err);
											uni.showToast({title: '请登录', icon: 'none', duration: 2000});
										}
									})
								} else {
									uni.showToast({title: '设备已存在列表中', icon: 'none', duration: 2000});
								}
								console.log('有效的deiceUUID：' + res.result); //111

							} else {
								uni.showToast({title: '扫描的内容不是有效的看护设备', icon: 'none', duration: 2000});
							}
						}
					});
				} else {
					uni.navigateTo({url: '/pages/home/home'})
				}
			},
			// 获取设备列表的方法
			getDeviceList() {
				uni.request({
					url: this.$baseUrl + '/user/device/getbyphone/' + this.phoneNumber, // 后端接口
					method: 'POST',
					data: {},
					header: {
						'content-type': 'application/x-www-form-urlencoded', // 请求头
						'token': uni.getStorageSync('token')
					},
					success: (res) => {
						if (res.statusCode === 200) {
							console.log('请求成功', res); //111222
							this.list = []; //清空之前的设备列表
							if (null != res.data.data) {
								// let temp_list = new Array(res.data.data.length);
								let temp_list = [];
								this.deviceUUIDlist = [];
								var j = 0;
								for (var i = 0; i < res.data.data.length; i++) {
									// 保存要订阅的UUID列表
									this.deviceUUIDlist.push(res.data.data[i].deviceUUID);
									// 根据类型显示列表
									if (res.data.data[i].type === 1) {		
										const isCurrentUser = res.data.data[i].phone === this.phoneNumber;
										temp_list[j] = {
											name: res.data.data[i].name + '--' +res.data.data[i].bed,
											uuid: res.data.data[i].deviceUUID,
											fontStyle: isCurrentUser ?
												'color: rgb(0, 0, 200) ; font-weight: bold; font-size: 38rpx' :
												'font-size: 30rpx'
										}
										j++;
									} 
								}
								console.log(this.deviceUUIDlist);
								uni.setStorageSync('uuidlist', this.deviceUUIDlist)
								this.list = temp_list; //根据请求返回的数据重新获取设备列表
								// 在成功获取设备列表后，订阅所有设备的主题
								this.subscribeToAllTopics();
								this.loadAudioChoices();
							}
						}
					},
					fail: (err) => {
						// 网络或其他错误处理
						console.error('请求错误：', err);
						uni.showToast({title: '请登录', icon: 'none', duration: 2000});
					}
				});
			},
			loadAudioChoices() {
				const uuid = this.deviceUUID;
				if (uuid) {
					this.deviceUUIDlist.forEach(uuid => {
						const choice = uni.getStorageSync(`audioChoice_${uuid}`) || 'default';
						this.audioChoice[uuid] = choice;
					});
				}
			},
			subscribeToAllTopics() {
				// 获取新的设备列表并订阅
				const deviceUUIDList = this.deviceUUIDlist;
				const subscribeInfoList = deviceUUIDList.map(uuid => ({topic: 'LSY/device/' + uuid, qos: 0}));

				this.subscribedTopics = uni.getStorageSync('subscribedTopics') || []; // 获取存储的所有订阅的topic
				// 取消订阅所有已订阅的主题
				this.subscribedTopics.forEach(topic => {
					client.unsubscribe(topic, (err) => {
						if (!err) {console.log(`Unsubscribed from ${topic}`);} 
						else {console.error(`Failed to unsubscribe from ${topic}:`, err);}
					});
				});	
				// 清空订阅主题列表
				uni.removeStorageSync('subscribedTopics');
				this.subscribedTopics = [];
				
				// 重新订阅所有主题
				this.subscribeInfo = subscribeInfoList;
				this.subscribeInfo.forEach(info => {
					if (!this.subscribedTopics.includes(info.topic)) {
						client.subscribe(info.topic, {qos: info.qos}, (err) => {
							if (!err) {
								console.log(`Subscribed to ${info.topic}`);
								this.subscribedTopics.push(info.topic);						
							}
						});
					}
				});
				uni.setStorageSync('subscribedTopics', this.subscribedTopics); // 更新本地存储的已订阅主题列表

				client.removeAllListeners('message');
				client.on('message', (topic, message) => {
					const messageStr = message.toString();
					console.log('首页收到消息topic：' + topic + ' msg:' + messageStr);

					if (!messageStr.trim()) { // 处理空消息	
						console.log('收到一个空消息，主题为:', topic);
						return; // 如果消息为空，退出处理程序
					}

					const currentUUID = topic.substring(11, topic.length);
					const choice = this.audioChoice[currentUUID] || 'default';

					// 找到对应的设备
					const device = this.list.find(item => item && item.uuid === currentUUID);
					let deviceName = device ? device.name : '用户';

					//------------------------20270711LuXiaochen--------------------------//					
					if (/battery/.test(messageStr)) {	// 处理收到的电量消息					
						const dataMatch = messageStr.match(/'data':'([^']+)'/); // 使用正则表达式从 messageStr 中提取 data (电量)的值
						let elec = dataMatch[1];
						uni.showModal({
							title: '设备电量提醒',
							content: `${deviceName}电量只有${elec}%了，请及时充电`,
							showCancel: false
						})
					}				
					//-------------------------------------------------------------------//
					if (/stop/.test(messageStr)) {	// 处理收到的停止消息				
						if (this.currentAudioContext) {
							this.currentAudioContext.stop();
							this.currentAudioContext = null;
							if (this.audioTimeout) {
								clearTimeout(this.audioTimeout);
								this.audioTimeout = null;
							}
							getApp().globalData.globalPlayMute = false; // 全局变量清零，播放静音文件
						}
						let nameMatch = messageStr.match(/'name':'([^']+)'/); // 使用正则表达式从 messageStr 中提取 name 的值
						if (!nameMatch) {
							nameMatch = messageStr.match(/"name":"([^']+)"/); // 使用正则表达式从 messageStr 中提取 name 的值
						}
						let name = nameMatch ? nameMatch[1] : '有人';
						uni.showModal({
							title: '有人响应',
							content: name + `响应了${deviceName}`,
							showCancel: false
						});
						return;
					}

					// 根据收到的消息内容进行处理
					if (this.deviceUUIDlist.includes(topic.split('/')[2])) {
						// 根据设备的audioChoice加载正确的音频路径
						let audioSrc = '';
						let modalContent = '';
						
						//------------------------20270717LuXiaochen--------------------------//
						if (/code/.test(messageStr) && /0/.test(messageStr)) {
							audioSrc = (choice === 'custom') ? (uni.getStorageSync(`userRecording${currentUUID}alarm`) || 
								this.defaultAudioPaths.alarm) : this.defaultAudioPaths.alarm;
							modalContent = `${deviceName} 发出了报警信号`;
						} 
						else if (/code/.test(messageStr) && /1/.test(messageStr)) {
							audioSrc = (choice === 'custom') ? (uni.getStorageSync(`userRecording${currentUUID}other`) || 
								this.defaultAudioPaths.other) : this.defaultAudioPaths.other;
							modalContent = `${deviceName} 发出了其他提醒`;
						} 
						else if (/code/.test(messageStr) && /2/.test(messageStr)) {
							audioSrc = (choice === 'custom') ? (uni.getStorageSync(`userRecording${currentUUID}sleep`) || 
								this.defaultAudioPaths.sleep) : this.defaultAudioPaths.sleep;
							modalContent = `${deviceName} 发出了想睡提醒`;
						} 
						else if (/code/.test(messageStr) && /3/.test(messageStr)) {
							audioSrc = (choice === 'custom') ? (uni.getStorageSync(`userRecording${currentUUID}timeup`) || 
								this.defaultAudioPaths.timeup) : this.defaultAudioPaths.timeup;
							modalContent = `${deviceName} 发出了到时提醒`;
						} 
						else if (/code/.test(messageStr) && /4/.test(messageStr)) {
							audioSrc = (choice === 'custom') ? (uni.getStorageSync(`userRecording${currentUUID}normal`) || 
								this.defaultAudioPaths.normal) : this.defaultAudioPaths.normal;
							modalContent = `${deviceName} 发出了正常提醒`;
						} 
						else if (/code/.test(messageStr) && /5/.test(messageStr)) {
							audioSrc = (choice === 'custom') ? (uni.getStorageSync(`userRecording${currentUUID}comforta`) || 
								this.defaultAudioPaths.comforta) : this.defaultAudioPaths.comforta;
							modalContent = `${deviceName} 发出了舒服提醒`;
						} 
						else if (/code/.test(messageStr) && /6/.test(messageStr)) {
							audioSrc = (choice === 'custom') ? (uni.getStorageSync(`userRecording${currentUUID}uncomforta`) || 
								this.defaultAudioPaths.uncomforta) : this.defaultAudioPaths.uncomforta;
							modalContent = `${deviceName} 发出了难受提醒`;
						}
						console.log(audioSrc);
						

						if (audioSrc !== '') {
							console.log('Play ', audioSrc);
							// 停止之前的音频播放
							if (this.currentAudioContext) {
								this.currentAudioContext.stop();
								this.currentAudioContext = null;
							}

							getApp().globalData.globalPlayMute = true; // 全局变量置位，停止播放静音文件
							// 使用 backgroundAudioManager 播放音频
							const backgroundAudioManager = uni.getBackgroundAudioManager();
							backgroundAudioManager.title = '设备提示音';
							backgroundAudioManager.epname = deviceName;
							backgroundAudioManager.src = audioSrc;
							this.currentAudioContext = backgroundAudioManager;

							// 定义停止音频播放和清理定时器的函数
							const stopAudioAndClearTimeout = () => {
								if (this.currentAudioContext) {
									this.currentAudioContext.stop();
									this.currentAudioContext = null;
									clearTimeout(this.audioTimeout);
									this.audioTimeout = null;
									console.log('音频播放已停止');
									getApp().globalData.globalPlayMute = false; // 全局变量清零，播放静音文件
								}
							};
							if (this.audioTimeout) {
								clearTimeout(this.audioTimeout);
								this.audioTimeout = null;
							}
							// 播放音频
							backgroundAudioManager.play();
							backgroundAudioManager.onPlay(() => {
								// console.log('开始播放');
							});

							// 设置播放结束后的处理，重新开始播放
							backgroundAudioManager.onEnded(() => {
								if (this.currentAudioContext) {
									// console.log('音频播放结束，重新开始播放');
									this.currentAudioContext.play();
								}
							});

							// 设置定时器在60秒后停止音频播放
							this.audioTimeout = setTimeout(stopAudioAndClearTimeout, 60000); // 60秒

							backgroundAudioManager.onError((res) => {
								console.log(res.errMsg);
								console.log(res.errCode);
							});

						}

						if (modalContent !== '') {
							// 发送确认消息到 'LSY/app/' + deviceUUID
							const responseTopic = 'LSY/app/' + currentUUID;
							const responseMessage = JSON.stringify({msg: "OK"});
							setTimeout(() => {
								client.publish(responseTopic, responseMessage, {qos: 0}, (err) => {
									if (err) {
										console.error(`Failed to publish message to ${responseTopic}:`, err);
									} else {
										console.log(`Published message to ${responseTopic}:`, responseMessage);
									}
								});
							}, 500);
							uni.showModal({
								title: "设备提示",
								content: `${modalContent}`,
								success: (res) => {
									if (res.confirm) {
										// 发送回应消息到 'LSY/app/' + deviceUUID
										const respondMessage = JSON.stringify({
											msg: uni.getStorageSync('userName') + "responded"
										});
										client.publish(responseTopic, respondMessage, {qos: 0}, (err) => {
											if (err) {
												console.error(`Failed to publish message to ${responseTopic}:`, err);
											} else {
												console.log(`Published message to ${responseTopic}:`, respondMessage);
											}
										});
									} 
									if (this.currentAudioContext) { // 用户确认或取消后清除定时器
										this.currentAudioContext.stop();
										this.currentAudioContext = null;
										if (this.audioTimeout) {
											clearTimeout(this.audioTimeout);
											this.audioTimeout = null;
										}
										getApp().globalData.globalPlayMute = false; // 全局变量清零，播放静音文件
									}
								}
							});
							uni.vibrateLong();
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.grid-dynamic-box {
		margin-bottom: 10px;
	}

	.text {
		font-size: 28rpx;
		// margin-top: 30%;
	}

	.text1 {
		// font-size: 35rpx;
		margin-top: 30%;
	}

	.grid-item-box {
		flex: 3;
		// position: relative;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: center;
		padding: 15px 0;
	}
</style>